package com.bp.api.comments;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.bp.vo.CommentsVO;
import com.bp.vo.UserInfoVO;
import com.common.enums.CommonCode;
import com.common.enums.SystemStatusEnum;
import com.common.model.PageModel;
import com.idp.biz.bpcomments.entity.BpComments;
import com.idp.biz.bpcomments.service.BpCommentsService;
import com.idp.biz.bppost.entity.BpPost;
import com.idp.biz.bppost.service.BpPostService;
import com.idp.biz.bpuser.entity.BpUser;
import com.idp.biz.bpuser.service.BpUserService;
import com.idp.biz.bpusermessage.entity.BpUserMessage;
import com.idp.biz.bpusermessage.service.BpUserMessageService;

/**
 * 点赞评论
 */
@RestController
@RequestMapping(value = "/api/comments/", method = RequestMethod.POST)
public class CommentsController {
    private static Logger logger = LoggerFactory.getLogger(CommentsController.class);

    @Autowired
    private BpUserService userService;
    @Autowired
    private BpPostService postService;
    @Autowired
    private BpCommentsService commentsService;
    @Autowired
    private BpUserMessageService messageService;

    @Autowired
    private StringRedisTemplate redis;

    /**
     * 分页查询评论列表
     */
    @CrossOrigin
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        PageModel<BpComments> page = new PageModel<>();
        try {
            Integer draw = StringUtils.isNotEmpty(request.getParameter("draw")) ? Integer.valueOf(request.getParameter("draw")) : 0;//页号
            Integer length = StringUtils.isNotEmpty(request.getParameter("length")) ? Integer.valueOf(request.getParameter("length")) : 0;//每页条数
            //Integer recordsFiltered = StringUtils.isNotEmpty(request.getParameter("recordsFiltered")) ? Integer.valueOf(request.getParameter("recordsFiltered")) : 0 ;//过滤后总条数
            Integer recordsTotal = StringUtils.isNotEmpty(request.getParameter("recordsTotal")) ? Integer.valueOf(request.getParameter("recordsTotal")) : 0;//总条数
            Integer start = StringUtils.isNotEmpty(request.getParameter("start")) ? Integer.valueOf(request.getParameter("start")) : 0;//起始条数
            page.setDraw(draw);
            page.setLength(length);
            // page.setRecordsFiltered(recordsFiltered);
            page.setRecordsTotal(recordsTotal);
            page.setStart(start);
            String token = request.getParameter("token");
            String postId = request.getParameter("postId");
            String commentsId = request.getParameter("commentsId");
            if (StringUtils.isEmpty(postId) && StringUtils.isEmpty(commentsId)) {
                json.put("code", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getValue());
                json.put("message", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getName());
                return json.toString();
            }
            BpUser user = userService.getByToken(token);

            BpComments bpComments = new BpComments();
            bpComments.setPostId(postId);
            bpComments.setStatus(CommonCode.CONTENT_IS_NORMAL.getValue());
            bpComments.setSymbol(CommonCode.Y.getValue());

            PageModel<BpComments> pageData = commentsService.findByPage(bpComments, page);
            List<BpComments> commentsList = pageData.getData();
            List<CommentsVO> commentsVoList = commentsToVo(user, commentsList);

            PageModel<CommentsVO> data = new PageModel<>();
            data.setData(commentsVoList);
            data.setDraw(pageData.getDraw());
            data.setLength(pageData.getLength());
            // data.setRecordsFiltered(recordsFiltered);
            data.setRecordsTotal(pageData.getRecordsTotal());
            data.setStart(pageData.getStart());

            json.put("data", data);
            json.put("code", SystemStatusEnum.SUCCESS.getValue());
            json.put("message", SystemStatusEnum.SUCCESS.getName());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("code", SystemStatusEnum.SERVERERROR.getValue());
            json.put("message", SystemStatusEnum.SERVERERROR.getName());
        }
        return json.toString();
    }

    /**
     * 发布点赞/评论
     *
     * @param request
     * @return
     */
    @CrossOrigin
    @RequestMapping("/publish")
    public String publish(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        try {
            String token = request.getParameter("token");
            String postId = request.getParameter("postId");
            String commentsId = request.getParameter("commentsId");
            String type = request.getParameter("type");//1点赞 2评论
            String content = request.getParameter("content");
            if (StringUtils.isEmpty(token) || (StringUtils.isEmpty(postId) && StringUtils.isEmpty(commentsId)) || StringUtils.isEmpty(type)) {
                json.put("code", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getValue());
                json.put("message", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getName());
                return json.toString();
            }
            if (type.equals(CommonCode.COMMENT_TYPE_P.getValue()) && StringUtils.isEmpty(content)) {
                json.put("code", SystemStatusEnum.COMMENT_IS_NOT_NULL.getValue());
                json.put("message", SystemStatusEnum.COMMENT_IS_NOT_NULL.getName());
                return json.toString();
            }
            String isLogin = redis.opsForValue().get(token);
            if (StringUtils.isEmpty(isLogin)) {
                json.put("code", SystemStatusEnum.TOKEN_FAILURE.getValue());
                json.put("message", SystemStatusEnum.TOKEN_FAILURE.getName());
                return json.toString();
            }
            BpUser user = userService.getByToken(token);
            if (user == null) {
                json.put("code", SystemStatusEnum.USER_IS_NULL.getValue());
                json.put("message", SystemStatusEnum.USER_IS_NULL.getName());
                return json.toJSONString();
            }
            BpPost post = new BpPost();
            BpComments comments = new BpComments();

            if (StringUtils.isNotEmpty(postId)) {
                post = postService.getById(postId);
                if (post == null) {
                    json.put("code", SystemStatusEnum.CONTENT_IS_NULL.getValue());
                    json.put("message", SystemStatusEnum.CONTENT_IS_NULL.getName());
                    return json.toJSONString();
                }
                if (!post.getStatus().equals(CommonCode.CONTENT_IS_NORMAL.getValue())) {
                    json.put("code", SystemStatusEnum.CONTENT_IS_SHIELDING.getValue());
                    json.put("message", SystemStatusEnum.CONTENT_IS_SHIELDING.getName());
                    return json.toJSONString();
                }
                if (post.getSymbol().equals(CommonCode.N.getValue())) {
                    json.put("code", SystemStatusEnum.CONTENT_IS_FAILURE.getValue());
                    json.put("message", SystemStatusEnum.CONTENT_IS_FAILURE.getName());
                    return json.toJSONString();
                }
            }
            if (StringUtils.isNotEmpty(commentsId)) {
                comments = commentsService.getById(commentsId);
                if (comments == null) {
                    json.put("code", SystemStatusEnum.CONTENT_IS_NULL.getValue());
                    json.put("message", SystemStatusEnum.CONTENT_IS_NULL.getName());
                    return json.toJSONString();
                }
                if (!post.getStatus().equals(CommonCode.CONTENT_IS_NORMAL.getValue())) {
                    json.put("code", SystemStatusEnum.CONTENT_IS_SHIELDING.getValue());
                    json.put("message", SystemStatusEnum.CONTENT_IS_SHIELDING.getName());
                    return json.toJSONString();
                }
                if (post.getSymbol().equals(CommonCode.N.getValue())) {
                    json.put("code", SystemStatusEnum.CONTENT_IS_FAILURE.getValue());
                    json.put("message", SystemStatusEnum.CONTENT_IS_FAILURE.getName());
                    return json.toJSONString();
                }
            }
            //点赞评论者id
            String commentsUserId = user.getId();
            if (type.equals(CommonCode.COMMENT_TYPE_D.getValue())) {
                praise(post, comments, commentsUserId, json);
            } else if (type.equals(CommonCode.COMMENT_TYPE_P.getValue())) {
                comments(post, comments, content, commentsUserId, json);
            }
            return json.toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("code", SystemStatusEnum.SERVERERROR.getValue());
            json.put("message", SystemStatusEnum.SERVERERROR.getName());
        }
        return json.toString();
    }

    /**
     * 点赞
     */
    private void praise(BpPost post, BpComments comments, String commentsUserId, JSONObject json) {
        BpComments bpComments = new BpComments();
        bpComments.setUserId(commentsUserId);
        if (post != null) {
            bpComments.setPostId(post.getId());
        }
        if (comments != null) {
            bpComments.setCommentsId(comments.getId());
        }
        bpComments.setStatus(CommonCode.CONTENT_IS_NORMAL.getValue());
        bpComments.setSymbol(CommonCode.Y.getValue());
        List<BpComments> list = commentsService.findBySearch(bpComments);
        if (list != null && list.size() > 0) {
            json.put("code", SystemStatusEnum.PRAISE_IS_NOT_NULL.getValue());
            json.put("message", SystemStatusEnum.PRAISE_IS_NOT_NULL.getName());
        } else {
        	String userId = "";
        	String postId = "";
        	String commentsId = "";
            BpComments data = new BpComments();
            if (post != null) {
                userId = post.getUserId();
                postId = post.getId();
            } else if (comments != null) {
                userId = comments.getUserId();
                commentsId = comments.getId();
            }
            data.setUserId(userId);
            data.setType(CommonCode.COMMENT_TYPE_D.getValue());
            data.setPostId(postId);
            data.setCommentsId(commentsId);
            data.setContent("");
            data.setCommentsUserId(commentsUserId);
            data.setIsClassic(CommonCode.N.getValue());
            data.setIsTop(CommonCode.N.getValue());
            data.setReleaseTime(new Date());
            data.setStatus(CommonCode.CONTENT_IS_NORMAL.getValue());
            data.setSymbol(CommonCode.Y.getValue());
            commentsService.add(data);
            saveMessage(data);
            json.put("code", SystemStatusEnum.SUCCESS.getValue());
            json.put("message", SystemStatusEnum.SUCCESS.getName());
        }
    }

    /**
     * 评论
     */
    private void comments(BpPost post, BpComments comments, String content, String commentsUserId, JSONObject json) {
        String userId = "";
        String postId = "";
        String commentsId = "";
        BpComments data = new BpComments();
        if (post != null) {
            userId = post.getUserId();
            postId = post.getId();
        } else if (comments != null) {
            userId = comments.getUserId();
            commentsId = comments.getId();
        }
        data.setUserId(userId);
        data.setType(CommonCode.COMMENT_TYPE_P.getValue());
        data.setPostId(postId);
        data.setCommentsId(commentsId);
        data.setContent(content);
        data.setCommentsUserId(commentsUserId);
        data.setIsClassic(CommonCode.N.getValue());
        data.setIsTop(CommonCode.N.getValue());
        data.setReleaseTime(new Date());
        data.setStatus(CommonCode.CONTENT_IS_NORMAL.getValue());
        data.setSymbol(CommonCode.Y.getValue());
        commentsService.add(data);
        saveMessage(data);
        json.put("code", SystemStatusEnum.SUCCESS.getValue());
        json.put("message", SystemStatusEnum.SUCCESS.getName());
    }

    /**
     * 保存用户消息
     */
    private void saveMessage(BpComments comments) {
        BpUserMessage userMessage = new BpUserMessage();
        userMessage.setUserId(comments.getUserId());
        userMessage.setType(comments.getType());
        userMessage.setPostId(comments.getPostId());
        userMessage.setCommentsId(comments.getCommentsId());
        userMessage.setCommentsUserId(comments.getCommentsUserId());
        userMessage.setTitle("");
        userMessage.setContent(comments.getContent());
        userMessage.setCreateTime(new Date());
        userMessage.setIsRead(CommonCode.N.getValue());
        userMessage.setSymbol(CommonCode.Y.getValue());
        userMessage.setRemark("");
        messageService.add(userMessage);
    }

    /**
     * 删除评论
     */
    @CrossOrigin
    @RequestMapping("/delete")
    public String delete(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        try {
            String token = request.getParameter("token");
            String commentsId = request.getParameter("commentsId");
            if (StringUtils.isEmpty(token) || StringUtils.isEmpty(commentsId)) {
                json.put("code", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getValue());
                json.put("message", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getName());
                return json.toString();
            }
            String isLogin = redis.opsForValue().get(token);
            if (StringUtils.isEmpty(isLogin)) {
                json.put("code", SystemStatusEnum.TOKEN_FAILURE.getValue());
                json.put("message", SystemStatusEnum.TOKEN_FAILURE.getName());
                return json.toString();
            }
            BpUser user = userService.getByToken(token);
            BpComments bpComments = new BpComments();
            bpComments.setCommentsId(commentsId);
            bpComments.setCommentsUserId(user.getId());
            bpComments.setStatus(CommonCode.CONTENT_IS_NORMAL.getValue());
            bpComments.setSymbol(CommonCode.Y.getValue());

            List<BpComments> commentsList = commentsService.findBySearch(bpComments);
            if (commentsList != null && commentsList.size() > 0) {
                BpComments comments = commentsList.get(0);
                comments.setStatus(CommonCode.CONTENT_IS_DELETE.getValue());
                comments.setSymbol(CommonCode.N.getValue());
                commentsService.update(comments);
            } else {
                json.put("code", SystemStatusEnum.NOT_DELETE_COMMENTS.getValue());
                json.put("message", SystemStatusEnum.NOT_DELETE_COMMENTS.getName());
                return json.toString();
            }
            json.put("code", SystemStatusEnum.SUCCESS.getValue());
            json.put("message", SystemStatusEnum.SUCCESS.getName());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("code", SystemStatusEnum.SERVERERROR.getValue());
            json.put("message", SystemStatusEnum.SERVERERROR.getName());
        }
        return json.toString();
    }

	/**
	 * 取消点赞
	 */
	@CrossOrigin
	@RequestMapping("/cancelPraise")
	public String cancelPraise(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		try {
			String token = request.getParameter("token");
			String postId = request.getParameter("postId");
			String commentsId = request.getParameter("commentsId");
			if(StringUtils.isEmpty(token) || StringUtils.isEmpty(postId)){
				json.put("code", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getValue());
				json.put("message", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getName());
				return json.toString();
			}
			String isLogin = redis.opsForValue().get(token);
			if(StringUtils.isEmpty(isLogin)){
				json.put("code", SystemStatusEnum.TOKEN_FAILURE.getValue());
				json.put("message", SystemStatusEnum.TOKEN_FAILURE.getName());
				return json.toString();
			}
			BpUser user = userService.getByToken(token);
			BpComments bpComments = new BpComments();
			if(StringUtils.isNotEmpty(commentsId)){
				bpComments.setId(commentsId);
			}
			if(StringUtils.isNotEmpty(postId)){
				bpComments.setPostId(postId);
			}
			bpComments.setCommentsUserId(user.getId());
			bpComments.setStatus(CommonCode.CONTENT_IS_NORMAL.getValue());
			bpComments.setSymbol(CommonCode.Y.getValue());
			List<BpComments> commentsList = commentsService.findBySearch(bpComments);
			if(commentsList != null && commentsList.size() > 0){
				BpComments comments = commentsList.get(0);
				comments.setStatus(CommonCode.CONTENT_IS_DELETE.getValue());
				comments.setSymbol(CommonCode.N.getValue());
				commentsService.update(comments);
				json.put("code", SystemStatusEnum.SUCCESS.getValue());
				json.put("message", SystemStatusEnum.SUCCESS.getName());
 			} else {
 				json.put("code", SystemStatusEnum.FAIL.getValue());
 				json.put("message", SystemStatusEnum.FAIL.getName());
 			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			json.put("code", SystemStatusEnum.SERVERERROR.getValue());
			json.put("message", SystemStatusEnum.SERVERERROR.getName());
		}
		return json.toString();
	}
    
    /**
     * 构建评论列表
     */
    private List<CommentsVO> commentsToVo(BpUser user, List<BpComments> commentsList) {
        List<CommentsVO> commentsVoList = new ArrayList<>();
        Integer praiseNum = 0;
        Integer commentsNum = 0;
        String isPraise = CommonCode.N.getValue();
        String isMyComments = CommonCode.N.getValue();
        for (BpComments comments : commentsList) {
            if (comments.getCommentsId().equals(comments.getId()) && comments.getType().equals(CommonCode.COMMENT_TYPE_D.getValue())) {
                praiseNum++;
            }
            if (comments.getCommentsId().equals(comments.getId()) && comments.getType().equals(CommonCode.COMMENT_TYPE_P.getValue())) {
                commentsNum++;
            }
            if (user != null) {
                if (comments.getType().equals(CommonCode.COMMENT_TYPE_D.getValue()) && comments.getCommentsUserId().equals(user.getId())) {
                    isPraise = CommonCode.Y.getValue();
                }
                if (comments.getType().equals(CommonCode.COMMENT_TYPE_P.getValue()) && comments.getCommentsUserId().equals(user.getId())) {
                    isMyComments = CommonCode.Y.getValue();
                }
            }
            CommentsVO commentsVO = new CommentsVO();
            commentsVO.setId(comments.getId());
            commentsVO.setType(comments.getType());
            commentsVO.setPostId(comments.getPostId());
            commentsVO.setCommentsId(comments.getCommentsId());
            commentsVO.setCommentsUserId(comments.getCommentsUserId());
            commentsVO.setContent(comments.getContent());
            commentsVO.setIsClassic(comments.getIsClassic());
            commentsVO.setIsTop(comments.getIsTop());
            commentsVO.setReleaseTime(comments.getReleaseTime());
            commentsVO.setUserInfo(getUserInfoVO(comments.getCommentsUserId()));
            commentsVO.setPraiseNum(praiseNum);
            commentsVO.setCommentsNum(commentsNum);
            commentsVO.setIsPraise(isPraise);
            commentsVO.setIsMyComments(isMyComments);
            commentsVoList.add(commentsVO);
        }
        return commentsVoList;
    }

    /**
     * 构建用户信息
     */
    private UserInfoVO getUserInfoVO(String userId) {
    	BpUser user = userService.getById(userId);
        UserInfoVO vo = new UserInfoVO();
        if (user != null) {
            vo.setId(user.getId() == null ? "" : user.getId());
            vo.setUserPhoto(user.getUserPhoto() == null ? "" : user.getUserPhoto());
            vo.setNickName(user.getNickName() == null ? "" : user.getNickName());
            vo.setSex(user.getSex() == null ? "" : user.getSex());
            vo.setUserType(user.getUserType() == null ? "" : user.getUserType());
        }
        return vo;
    }

}
